#include "TCPServer.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <string>
#include "../Stringops/StringOps.h"
using namespace std;

int buildClient(int argc, char*argv[]);

int main(int argc, char*argv[]){
	int mainRtn = 0;
	mainRtn = buildClient(argc, argv);
	if(mainRtn < 0) {
		exit(EXIT_FAILURE);	
	}
	return mainRtn;	
}

bool ipcheck(std::string _host) {
        std::vector<std::string> parts = split(_host, '.');
        for(unsigned int i = 0; i < parts.size(); i++)
                if(!is_numeric(parts[i]))
                        return false;
        return true;
}

int buildClient(int argc, char*argv[]){
	string _serv_port;
	string _serv_ip;
	string _raw_port;
	string _burst_time;
	string _round_time;
	string _delta_sec;
	if(argc!=7){
		printf("correct command:<client> <server ip> <server port> <raw port> <burst time> <round time> <delta>\n");
		return 1;
	}else{
		_round_time = argv[5];
		_burst_time = argv[4];
		_raw_port = argv[3];
		_serv_port = argv[2];
		_serv_ip = argv[1];
		_delta_sec = argv[6];
		if(ipcheck(_serv_ip) && is_numeric(_serv_port) && is_numeric(_raw_port) 
		&& is_numeric(_burst_time) && is_numeric(_round_time) && is_numeric(_delta_sec)){
			TCPConnection cliConn(_serv_ip, atoi(_serv_port.c_str()), atoi(_raw_port.c_str()),
					atoi(_burst_time.c_str()), atoi(_round_time.c_str()), atoi(_delta_sec.c_str()));
			if(cliConn.sock == null) {
				// Failed to establish connection; terminate
				return -1;
			}
			cliConn.handle_client_connection();
			cliConn.close_connection();
		}else{
			printf("command format is not right!\n");
			return 1;
		}
		return 0;
	}
	return 0;
}
